package com.person.ntv.controller.sys;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.person.Constants;
import com.person.layui.Menu;
import com.person.login.CreateImage;
import com.person.ntv.entity.sys.SysUser;
import com.person.ntv.service.sys.CommonService;
import com.person.ntv.service.sys.SysPropertyService;
import com.person.ntv.service.sys.SysResourceService;
import com.person.ntv.service.sys.SysUserService;

@Controller
@RequestMapping("/system/sysLogin")
public class SysLoginController {
	@Autowired
	private CommonService commonService ;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysPropertyService sysPropertyService;
	@Autowired
	private SysResourceService sysResourceService;
	
	@RequestMapping("/loginPage")
	public String  loginPage(ModelMap mv,HttpServletRequest request){
		    //判断是否已经登录
		    if(request.getSession().getAttribute(Constants.CURRENT_USER)!=null){
		    	return "main";
		    }
		    String exceptionClassName = (String)request.getAttribute("shiroLoginFailure");
	        String error = null;
	        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
	            error = "用户名/密码错误";
	        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
	            error = "用户名/密码错误";
	        } else if("jCaptcha.error".equals(exceptionClassName)) {
	            error = "验证码错误";
	        }else if(org.apache.shiro.authc.ExcessiveAttemptsException.class.getName().equals(exceptionClassName)){
	        	error="账号被锁定或禁用！";
	        }else if(exceptionClassName != null) {
	            error = "其他错误：" + exceptionClassName;
	        }else if("1".equals(request.getParameter("kickout"))){
	        	error="账号被其他人登录！";
	        }
	        mv.addAttribute("error", error);
		return "/login";
	}
	
	@RequestMapping("/loginSuccess")
	public String  loginSuccess(ModelMap mv,HttpServletRequest request,HttpServletResponse response) throws Exception{
				//获取个人属性设置
		        SysUser currentUser = (SysUser)request.getSession().getAttribute(Constants.CURRENT_USER);
				List<Map<String,Object>>userProperties=sysPropertyService.getUserProperties(String.valueOf(currentUser.getId()));
				Map<String,Object>currentProperties=new HashMap<String,Object>();
				for(Map<String,Object>tmp:userProperties){
					currentProperties.put(tmp.get("propertyName").toString(),tmp.get("userPropertyValue")==null?tmp.get("propertyValue"):tmp.get("userPropertyValue"));
				}
			   //查询菜单
				Map<String,String> params=new HashMap<String,String>();
				SysUser sysUser=(SysUser)request.getSession().getAttribute(Constants.CURRENT_USER);
				params.put("resType","1");
				params.put("userId",sysUser.getId().toString());
				params.put("parentIds", "1");
			    List<Map<String,Object>> list = sysResourceService.getMenuTree(params);
			    List<Menu> result=new ArrayList<Menu>();
			    if(list!=null&&list.size()>0){
			    	result=Menu.listToMenus("1",list);
				}
			    request.getSession().setAttribute("menuList",result);
				return "/main";
	}
	 
	/**
	 * 退出系统
	 * @author lqy
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model model)
	{
		session.invalidate();
		return "/login";
	}
	
	@RequestMapping("/validateImg")
	public void validateImg(HttpServletRequest request,HttpServletResponse response)
	{
		   CreateImage ci=new CreateImage();
		   BufferedImage image=ci.createImage();
		   response.setHeader("Pragma", "no-cache");
		   response.setHeader("Cache-Control", "no-cache");
		   response.setDateHeader("Expires", 0);
		   response.setContentType("image/jpeg");
	       HttpSession session = request.getSession();
	       String code=ci.getCode();
	       session.setAttribute("verifyCode",code);
	       ByteArrayOutputStream os = new  ByteArrayOutputStream();
	      // 将图像输出到Servlet输出流中。  
	        ServletOutputStream sos;
			try {
				ImageIO.write(image, "jpeg", os);
				sos = response.getOutputStream();
				sos.write(os.toByteArray());
				sos.flush();
			    sos.close();
			} catch (Exception e) {
				e.printStackTrace();
			} 
	}	
}
